/**********************************************************************************
 * Copyright (c) 2012 - 2012,  parallel, All right reserved
 * Title: com.adc.parallel.daemon  MainDaemonThread.java 
 * @author shen  shenqiao2012@163.com 
 *  2012-11-22 下午11:26:23 
 *********************************************************************************/


package com.adc.parallel.daemon;

import java.util.List;

import com.adc.parallel.constants.CompleteList;
import com.adc.parallel.constants.ReceiveList;
import com.adc.parallel.constants.RuntimeList;
import com.adc.parallel.constants.SysConstants;
import com.adc.parallel.constants.ThreadConstant;
import com.adc.parallel.constants.WaitList;
import com.adc.parallel.control.InitGlobalVariable;



public class MainDaemonThread extends BaseTimerThread {
	private boolean quit=true;

	/** 
	* @param maxLive
	* @param cycle    
	 */
	public MainDaemonThread() {
		super(ThreadConstant.getPersistentCycle()/3, ThreadConstant.getPersistentCycle()/3);
		this.setName(SysConstants.getDaemonThreadName("Controller"));
	}

	/**
	 * Description:  
	 * @see com.adc.parallel.daemon.BaseTimerThread#operaPerCycle() 
	 */
	@Override
	public int operaPerCycle() {
		// TODO Auto-generated method stub
		if (checkTaskList(ReceiveList.getReceiveList(), WaitList.getWaitList(), 
				RuntimeList.getRuntimeList(), CompleteList.getCompleteList())) {
			System.out.println("Exiting Parallel Application!");
			SysConstants.setExitMain(quit);
			this.setExit(quit);
		}
		return 0;
	}

	/**
	 * Description:  
	 * @see com.adc.parallel.daemon.BaseTimerThread#operaOnTimeOut() 
	 */
	@Override
	public int operaOnTimeOut() {
		// TODO Auto-generated method stub
		return 0;
	}
	
	/**
	 * 
	 * Description: check status,when all task is over,then quit
	 * author:  shen
	 * @param reList
	 * @param wtList
	 * @param rtList
	 * @param cpList
	 * @return boolean
	 */
	@SuppressWarnings("rawtypes")
	private boolean checkTaskList(final List reList,final List wtList,final List rtList,final List cpList) {
		boolean result=false;
		if (reList.size()==0) {
			InitGlobalVariable.getReceiveDaemonThread().setExit(quit);
			if (wtList.size()==0&&rtList.size()==0) {
				InitGlobalVariable.getWaitDaemonThread().setExit(quit);
				try {
					sleep(ThreadConstant.getClearCompletedTime()*2);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				InitGlobalVariable.getRuntimeDaemonThread().setExit(quit);
				if (cpList.size()==0) {
					InitGlobalVariable.getCompleteDaemonThread().setExit(quit);
					result=true;
				}
			}
		}
		return result;
	}

}
